const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const path = require('path')
const router = require('./routes/router')
const session = require('express-session')
const log4js = require('log4js')
const multer = require('multer')

app.use('/public/', express.static(path.join(__dirname, './public/')))
app.use(
  '/node_modules/',
  express.static(path.join(__dirname, './node_modules/'))
)
app.engine('html', require('express-art-template'))
app.set('views', __dirname + '/views')

app.use(
  session({
    secret: 'ocr', // 对session id 相关的cookie 进行签名
    resave: true,
    saveUninitialized: false, // 是否保存未初始化的会话
    cookie: {
      maxAge: 1000 * 60 * 30, // 设置 session 的有效时间，单位毫秒
    },
  })
)
// interceptor
app.all('/*', function (req, res, next) {
  if (req.session.user || app.all('/api/*')) {
    next()
  } else {
    var arr = req.url.split('/') // 解析用户请求的路径
    console.log(arr.length)

    for (let i = 0, length = arr.length; i < length; i++) {
      // 去除 GET 请求路径上携带的参数
      arr[i] = arr[i].split('?')[0]
    }
    if (arr.length > 1 && arr[1] == '') {
      // 判断请求路径是否为根、登录、注册、登出，如果是不做拦截
      next()
    } else if (
      arr.length > 1 &&
      (arr[1] == 'register' ||
        arr[1] == 'login' ||
        arr[1] == 'logout' ||
        arr[1].indexOf('login') > 0)
    ) {
      next()
    } else {
      // 登录拦截
      req.session.originalUrl = req.originalUrl ? req.originalUrl : null // 记录用户原始请求路径
      res.redirect('/login') // 将用户重定向到登录页面
    }
  }
})
process.on('unhandledRejection', (reason, p) => {
  console.log('Unhandled Rejection at: Promise', p, 'reason:', reason)
  // application specific logging, throwing an error, or other logic here
})

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(router)
// 设置跨域和响应数据格式
app.all('/api/*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, mytoken')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, Authorization')
  res.setHeader('Content-Type', 'application/json;charset=utf-8')
  res.header(
    'Access-Control-Allow-Headers',
    'Content-Type,Content-Length, Authorization, Accept,X-Requested-With'
  )
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
  res.header('X-Powered-By', ' 3.2.1')
  if (req.method == 'OPTIONS') res.send(200)
  /*让options请求快速返回*/ else next()
})

app.listen(3000, () => {
  console.log('server is running ' + 3000)
})
